﻿

( function() {
	"use strict";

	// WinJS shortcuts and namespaces.
	var Launcher = Windows.System.Launcher;
	var NetworkInformation = Windows.Networking.Connectivity.NetworkInformation;
	var NetworkConnectivityLevel = Windows.Networking.Connectivity.NetworkConnectivityLevel;
	var Uri = Windows.Foundation.Uri;


	// ----------------------------------------------------------------------------------------------
	//   CLASS REGISTRATION WITH PUBLIC MEMBERS
	// ----------------------------------------------------------------------------------------------

	WinJS.Namespace.define( 'WinJSTK', {
		
		isConnected: function() {
			/// <summary>Detects whether the device has connection to the internet. Returns True, if the device connects to the internet, otherwise false.</summary>
			/// <returns type="Boolean">True, if the device connects to the internet, otherwise false.</returns>

			var profile = NetworkInformation.getInternetConnectionProfile();

			if( profile !== null ) {
				var level = profile.getNetworkConnectivityLevel();
				return level === NetworkConnectivityLevel.constrainedInternetAccess || level === NetworkConnectivityLevel.internetAccess;
			}

			return false;
		},
		
		composeMailAsync: function( to, subject, body ) {
			/// <summary>Asynchronously starts the default e-mail sending application and composes a mail with the specified settings. Returns a Boolean promise that indicates the result of the operation.</summary>
			/// <param name="to" type="String">The e-mail address of the recipient of the e-mail.</param>
			/// <param name="subject" type="String">The subject of the e-mail.</param>
			/// <param name="body" type="String">The text of the e-mail body.</param>
			/// <returns type="WinJS.Promise">A WinJS.Promise object with a Boolean value that is true if the mail is composed successfully, otherwise false.</returns>

			var uri = new Uri( 'mailto:{0}?subject={1}&body={2}'.format( to, subject, body ) );
			return Launcher.launchUriAsync( uri );
		}
		
	} );

} )();



// --------------------------------------------------------------------------------------------
//  PROTOTYPES (aka extension methods)
// --------------------------------------------------------------------------------------------

String.prototype.format = function() {
	/// <summary>
	/// Substitutes the placeholders ({0}, {1} etc.) in the current string with the values given as parameters. (WinJSToolkit)
	/// </summary>
	/// <param name="arguments" type="Array" optional="false">The values that should be substituted.</param>
	/// <returns type="String">The original string with values substituted into the placeholders.</returns>

	var args = arguments;
	return this.replace( /\{\{|\}\}|\{(\d+)\}/g, function( m, n ) {
		if( m === "{{" ) { return "{"; }
		if( m === "}}" ) { return "}"; }
		return args[n];
	} );
};

